package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServerletRequest {
    private Socket socket;
    //成员变量(请求相关信息）
    private String method;
    private String uri;
    private String protocol;
    private Map<String,String> headers = new HashMap<>();
    public HttpServerletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析正文
        parseContent();
    }
    //1.处理请求行
    public void parseRequestLine() throws IOException {
        String line = readLine();
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol"+protocol);
    }

    //1.2解析消息头
    public void parseHeaders() throws IOException {
        while (true){
            String line = readLine();
            if (line.isEmpty()){
                break;
            }
            System.out.println("消息头："+line);
            String[] data = line.split(":\\s");
            System.out.println("headers：");
            headers.put(data[0], data[1]);
        }
        System.out.println("消息头："+headers);
    }

    //1.3解析消息正文
    public void parseContent(){

    }


    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';
        char pre = 'a';
        int d;
        while ((d= in.read()) != -1){
            cur = (char) d;
            if (pre==13 && cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeaders(String name){
        return headers.get(name);
    }
}
